import 'package:auto_route/auto_route.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_sliver_grid.dart';
import 'package:casdon/common/widget/common_sliver_list_widget.dart';
import 'package:casdon/modules/recipe/data/model/recipe_category_model.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:casdon/modules/recipe/ui/widgets/recipe_category_item.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class RecipeCategoryScreen extends ConsumerWidget {
  const RecipeCategoryScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final recipecategoryAsyState = ref.read(recipeCategoryAsyncProvider);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(title: "全部分类"),
      body: SafeArea(
        child: CustomScrollView(
          slivers: [
            SliverAsyncListView<RecipeCategoryModel>(
              asyncData: recipecategoryAsyState.whenData((s) => s.data),
              sliverBuilder: (context, data) =>
                  CommonSliverGrid<RecipeCategoryData>(
                    padding: EdgeInsets.all(16.w),
                    crossAxisCount: 4,
                    items: data,
                    itemBuilder: _buildCategoryItem,
                  ),
              onRetry: () => {},
            ),
          ],
        ),
      ),
    );
  }

  // 构建菜谱分类Item
  Widget _buildCategoryItem(
    BuildContext context,
    RecipeCategoryData item,
    int index,
  ) {
    RecipeCategoryData newItem = item;
    onTap(RecipeCategoryData? item) {
      if (item == null) {
        return;
      }
      // 进入菜谱分类二级页面
      RecipeCategoryDetailRoute(id: item.id, title: item.title).push(context);
    }

    return RecipeCategoryItem(item: newItem, onTap: onTap);
  }
}
